iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
自我挑戰組

開學之前....系列 第 8

Day8-169. Majority Element

  • 分享至 

  • xImage
  •  

今日題目:169. Majority Element(easy)

Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Example 1:
Input: nums = [3,2,3]
Output: 3

Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2

Constraints:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -231 <= nums[i] <= 231 - 1
    Follow-up: Could you solve the problem in linear time and in O(1) space?

My solution

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort()
        return nums[len(nums)//2]

Result

https://ithelp.ithome.com.tw/upload/images/20210923/20140843alXg6CVwxP.png


上一篇
Day7 -104. Maximum Depth of Binary Tree
下一篇
Day10-119. Pascal's Triangle II
系列文
開學之前....20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言